import { Component, OnInit, Input, Output, EventEmitter, OnChanges } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'el-checkbox-group',
  templateUrl: './checkbox-group.component.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: CheckboxGroupComponent,
    multi: true
  }],
})
export class CheckboxGroupComponent implements OnInit, OnChanges, ControlValueAccessor {
  @Input() disabled: boolean = false;
  @Input() size: string = '';
  @Input() fill: string = '#20a0ff';
  @Input() textColor: string = '#ffffff';
  @Input() min: number = 0;
  @Input() max: number = 1000;
  @Input() model: any = [];
  @Output() modelChange: EventEmitter<any> = new EventEmitter();
  @Input() subscriber: Function[] = [];
  private controlChange: any = function () { };
  private controlTouch: any = function () { };

  constructor() { }

  writeValue(obj: any): void {
    this.model = obj;
  }
  registerOnChange(fn: any): void {
    this.controlChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.controlTouch = fn;
  }

  changeModel(nextValue: any) {
    this.model = nextValue;
    this.modelChange.emit(nextValue);
    this.controlChange(nextValue);
    this.subscriber.forEach(function (sub) { return sub(); });
    return;
  }

  updateModelFromChildren(t: any, label: any) {
    // add label value
    if (t && this.model.indexOf(label) === -1) {
      if (this.model.length >= this.max)
        return;
      this.model.push(label);
    }
    // remove label value
    if (!t && this.model.indexOf(label) > -1) {
      if (this.model.length < this.min)
        return;
      this.model = this.model.map(function (v: any) { return v === label ? null : v; })
        .filter(function (v: any) { return v; });
    }
    // synchronize host
    this.changeModel(this.model);
    return;
  }

  ngOnChanges(changes: any) {
    if (!changes || !changes.model)
      return;
    if (changes.model.isFirstChange())
      return;
    this.changeModel(changes.model.currentValue);
  }
  ngOnInit(): void {
  }

}
